import { computed } from 'vue'

function useVModel<T extends Record<string, any>>(
  props: T,
  propName: keyof T & string,
  emit: Function
) {
  const model = computed({
    get() {
      const proxy = new Proxy(props[propName], {
        get(target, key) {
          return Reflect.get(target, key)
        },
        set(target, key, value) {
          emit('update:' + propName, {
            ...target,
            [key]: value
          })
          return true
        }
      })
      return proxy
    },
    set(newValue) {
      emit('update:' + propName, newValue)
    }
  })

  return model
}

export default useVModel
